package com.mach.platform.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import com.mach.platform.domain.Response;
import com.mach.platform.service.CarbonServiceImpl;
import com.mach.platform.service.IotDevServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.ss.usermodel.Workbook;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.NumberFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Administrator
 * @Description: 碳排放数据 请求
 * @Package: com.mach.platform.controller
 * @time 2018/6/12 0012 12:21
 */
@Api(tags = { "能源监控---碳排&对比" })
@RestController
@RequestMapping(value = "$carbon")
public class CarbonCtrl {

	@Autowired
	private CarbonServiceImpl carbonService;
	@Autowired
	private IotDevServiceImpl iotDevService;

	/**
	 * 汇总碳排,单车碳排,综合产量
	 *
	 * @param target 对象
	 * @param stime  开始时间
	 * @param etime  借宿时间
	 * @return Response
	 */
	@PostMapping("/total")
	@ApiOperation(value = "汇总碳排,单车碳排,综合产量", notes = "接口备注：将t1,t2,t3依次填上", produces = "application/json")
	public Response total (@ApiParam(name = "target", value = "对象") @RequestParam("target") String target,
			@ApiParam(name = "stime", value = "开始时间") @RequestParam(value = "stime", required = false) String stime,
			@ApiParam(name = "etime", value = "开结束时间") @RequestParam(value = "etime", required = false) String etime) {

		Map finalMap = Maps.newHashMapWithExpectedSize(3);

		/**virtaul  start**/
		Random random = new Random();
		NumberFormat numberFormat = NumberFormat.getPercentInstance();
		numberFormat.setMinimumFractionDigits(2);
		int productions = random.nextInt(1777) + 8000 + random.nextInt(1888);
		int unitCarbonNum = random.nextInt(1888) + 500;
		Map t1 = Maps.newHashMapWithExpectedSize(4);
		t1.put("total", productions * unitCarbonNum);
		t1.put("sameCompare", numberFormat.format(random.nextDouble()));
		t1.put("lastCompare", numberFormat.format(random.nextDouble()));
		t1.put("kpi", numberFormat.format(random.nextDouble()));
		finalMap.put("t1", t1);

		Map t2 = Maps.newHashMapWithExpectedSize(4);
		t2.put("total", unitCarbonNum);
		t2.put("sameCompare", numberFormat.format(random.nextDouble()));
		t2.put("lastCompare", numberFormat.format(random.nextDouble()));
		t2.put("kpi", numberFormat.format(random.nextDouble()));
		finalMap.put("t2", t2);

		Map t3 = Maps.newHashMapWithExpectedSize(4);
		t3.put("total", productions);
		t3.put("sameCompare", numberFormat.format(random.nextDouble()));
		t3.put("lastCompare", numberFormat.format(random.nextDouble()));
		t3.put("kpi", numberFormat.format(random.nextDouble()));
		finalMap.put("t3", t3);

		/**virtaul  end**/

		return Response.ok(finalMap);
	}

	/**
	 * 单类能源碳排
	 *
	 * @param target 对象
	 * @param stime  开始时间
	 * @param etime  借宿时间
	 * @return Response
	 */
	@PostMapping("/energy")
	@ApiOperation(value = "单类能源碳排", notes = "接口备注：将数组依次填上", produces = "application/json")
	public Response energy (@ApiParam(name = "target", value = "对象") @RequestParam("target") String target,
			@ApiParam(name = "stime", value = "开始时间") @RequestParam(value = "stime", required = false) String stime,
			@ApiParam(name = "etime", value = "开结束时间") @RequestParam(value = "etime", required = false) String etime) {

		List<Map> finalList = Lists.newArrayList();

		/**virtaul  start**/
		Random random = new Random();
		NumberFormat numberFormat = NumberFormat.getPercentInstance();
		numberFormat.setMinimumFractionDigits(2);

		for (int i = 0; i < 6; i++) {

			Map tempMap = Maps.newHashMap();
			int totals = random.nextInt(10000) + 22222;
			int avg = random.nextInt(1888);
			tempMap.put("total", totals);
			tempMap.put("avg", avg);
			tempMap.put("kpiTotal", totals + random.nextInt(1888));
			tempMap.put("kpiAvg", avg + random.nextInt(500));

			finalList.add(tempMap);
		}

		/**virtaul  send**/

		return Response.ok(finalList);
	}

	/**
	 * 汇总--碳排走势
	 *
	 * @param target 对象
	 * @param stime  开始时间
	 * @param etime  借宿时间
	 * @return Response
	 */
	@PostMapping("/total&chart")
	@ApiOperation(value = "汇总--碳排走势", notes = "接口备注：将数组依次填上", produces = "application/json")
	public Response totalCahrt (@ApiParam(name = "target", value = "对象") @RequestParam("target") String target,
			@ApiParam(name = "stime", value = "开始时间") @RequestParam(value = "stime", required = false) String stime,
			@ApiParam(name = "etime", value = "开结束时间") @RequestParam(value = "etime", required = false) String etime) {

		Map finalMap = Maps.newHashMapWithExpectedSize(3);

		/**virtaul  start**/
		Random random = new Random();

		List<String> times = Lists.newArrayList();
		List<Integer> yaxis1 = Lists.newArrayList();
		List<Integer> yaxis2 = Lists.newArrayList();

		for (int i = 1; i < 13; i++) {
			times.add(i + "月");
			yaxis1.add(random.nextInt(288888) + 129090);
			yaxis2.add(random.nextInt(288888) + 169090);
		}

		finalMap.put("xaxis", times);

		finalMap.put("legend", Stream.of("实际碳排量", "计划碳排量"));

		finalMap.put("yaxis1", yaxis1);
		finalMap.put("yaxis2", yaxis2);

		/**virtaul  send**/

		return Response.ok(finalMap);
	}

	/**
	 * 单车--碳排走势
	 *
	 * @param target 对象
	 * @param stime  开始时间
	 * @param etime  借宿时间
	 * @return Response
	 */
	@PostMapping("/avg&chart")
	@ApiOperation(value = "单车--碳排走势", notes = "接口备注：将数组依次填上", produces = "application/json")
	public Response avgCahrt (@ApiParam(name = "target", value = "对象") @RequestParam("target") String target,
			@ApiParam(name = "stime", value = "开始时间") @RequestParam(value = "stime", required = false) String stime,
			@ApiParam(name = "etime", value = "开结束时间") @RequestParam(value = "etime", required = false) String etime) {

		Map finalMap = Maps.newHashMapWithExpectedSize(3);

		/**virtaul  start**/
		Random random = new Random();

		List<String> times = Lists.newArrayList();
		List<Integer> yaxis1 = Lists.newArrayList();
		List<Integer> yaxis2 = Lists.newArrayList();

		for (int i = 1; i < 13; i++) {
			times.add(i + "月");
			yaxis1.add(random.nextInt(28888) + 12909);
			yaxis2.add(random.nextInt(28888) + 16909);
		}

		finalMap.put("xaxis", times);

		finalMap.put("legend", Stream.of("实际碳排量", "计划碳排量"));

		finalMap.put("yaxis1", yaxis1);
		finalMap.put("yaxis2", yaxis2);

		/**virtaul  send**/

		return Response.ok(finalMap);
	}

	/**
	 * 汇总--子级对比
	 *
	 * @param target 对象
	 * @param stime  开始时间
	 * @param etime  借宿时间
	 * @return Response
	 */
	@PostMapping("/total&sublevel&chart")
	@ApiOperation(value = "汇总--子级对比", notes = "接口备注：饼图数据已排序", produces = "application/json")
	public Response totalSonCahrt (@ApiParam(name = "target", value = "对象") @RequestParam("target") String target,
			@ApiParam(name = "stime", value = "开始时间") @RequestParam(value = "stime", required = false) String stime,
			@ApiParam(name = "etime", value = "开结束时间") @RequestParam(value = "etime", required = false) String etime) {

		Map finalMap = Maps.newHashMapWithExpectedSize(3);

		/**virtaul  start**/
		Random random = new Random();

		List<Map> data = Lists.newArrayList();

		List<String> factNames = Stream.of("HD1", "HD2", "DL", "XY", "ZZ", "CD").collect(Collectors.toList());

		for (int i = 0; i < factNames.size(); i++) {

			Map tempMap = Maps.newHashMap();
			tempMap.put("name", factNames.get(i));
			tempMap.put("value", random.nextInt(2888888) + 1129090);
			data.add(tempMap);
		}

		Ordering<Map> orderingRule = new Ordering<Map>() {
			@Override
			public int compare (Map map, Map t1) {
				return Integer.parseInt(t1.get("value").toString()) - Integer.parseInt(map.get("value").toString());
			}
		};

		data = orderingRule.sortedCopy(data);

		finalMap.put("legend", factNames);
		finalMap.put("data", data);

		/**virtaul  send**/

		return Response.ok(finalMap);
	}

	/**
	 * 单车--子级对比
	 *
	 * @param target 对象
	 * @param stime  开始时间
	 * @param etime  借宿时间
	 * @return Response
	 */
	@PostMapping("/avg&sublevel&chart")
	@ApiOperation(value = "单车--子级对比", notes = "接口备注：饼图数据已排序", produces = "application/json")
	public Response avgSbulevelCahrt (@ApiParam(name = "target", value = "对象") @RequestParam("target") String target,
			@ApiParam(name = "stime", value = "开始时间") @RequestParam(value = "stime", required = false) String stime,
			@ApiParam(name = "etime", value = "开结束时间") @RequestParam(value = "etime", required = false) String etime) {

		Map finalMap = Maps.newHashMapWithExpectedSize(3);

		/**virtaul  start**/
		Random random = new Random();
		List<Map> data = Lists.newArrayList();

		List<String> factNames = Stream.of("HD1", "HD2", "DL", "XY", "ZZ", "CD").collect(Collectors.toList());

		for (int i = 0; i < factNames.size(); i++) {

			Map tempMap = Maps.newHashMap();
			tempMap.put("name", factNames.get(i));
			tempMap.put("value", random.nextInt(28888) + 11290);
			data.add(tempMap);
		}

		Ordering<Map> orderingRule = new Ordering<Map>() {
			@Override
			public int compare (Map map, Map t1) {
				return Integer.parseInt(t1.get("value").toString()) - Integer.parseInt(map.get("value").toString());
			}
		};

		data = orderingRule.sortedCopy(data);

		finalMap.put("legend", factNames);
		finalMap.put("data", data);

		/**virtaul  send**/

		return Response.ok(finalMap);
	}

	/**
	 * 工厂数据对比
	 * @param json 参数
	 * @return
	 */
//	@PostMapping("factoryComparison")
//	@ApiOperation(value = "工厂数据对比", notes = "接口备注", produces = "application/json")
//	public Response factoryComparison(@ApiParam(name = "json", value = "参数json", required = true) @RequestParam("json") String json) {
//		Map resultData = iotDevService.factoryComparison(json);
//		return Response.ok(resultData);
//	}

	/**
	 * 车间数据对比
	 * @param json 参数
	 * @return
	 */
//	@PostMapping("workshopComparison")
//	@ApiOperation(value = "车间数据对比", notes = "接口备注", produces = "application/json")
//	public Response workshopComparison(@ApiParam(name = "json", value = "参数json", required = true) @RequestParam("json") String json) {
//		Map resultData = iotDevService.workshopComparison(json);
//		return Response.ok(resultData);
//	}

	/**
	 * 自定义--对比
	 * @param params 参数
	 * @return Response
	 */
	@PostMapping("customizeComparison")
	@ApiOperation(value = "自定义数据对比", notes = "接口备注：传参 json", produces = "application/json")
	public Response customizeComparison(@RequestBody Map params) {
		List resultData = iotDevService.customizeComparison(params);
		return Response.ok(resultData);
	}

	/**
	 * 获取 各能源的  碳排量和 单车碳排量
	 *
	 * @return
	 */
	@ApiOperation(value = "获取 各能源的  碳排量和 单车碳排量", notes = "接口备注：queryTotalObj : 以及 enName  合在一起", produces = "application/json")
	@PostMapping("carbon")
	public Response carbonCosumed (@RequestParam Map<String, Object> params) {

		if (params.get("timeType") == null || params.get("dateStr") == null || params.get("target") == null) {
			return Response.error("没有传必要的参数");
		}

		if ("日度".equals(params.get("timeType").toString())) {
			return Response.ok(Collections.emptyMap());
		}

		Map result = carbonService.carbonCosumed(params);

		return Response.ok(result);
	}

	@ApiOperation(value = "获取 碳排量趋势", notes = "接口备注：queryTotalObj : 以及 enName  合在一起", produces = "application/json")
	@PostMapping("trend")
	public Response carbonTrend (@RequestParam Map<String, Object> params) {

		if (params.get("timeType") == null || params.get("dateStr") == null || params.get("target") == null) {
			return Response.error("没有传必要的参数");
		}

		if ("月度".equals(params.get("timeType").toString())) {
			return Response.error("数据库没有天数据！");
		}

		Map result = carbonService.carbonTrend(params);

		return Response.ok(result);
	}

	@ApiOperation(value = "获取 单车碳排量 趋势", notes = "接口备注：queryTotalObj : 以及 enName  合在一起", produces = "application/json")
	@PostMapping("trendAvg")
	public Response carbonTrendAvg (@RequestParam Map<String, Object> params) {

		if (params.get("timeType") == null || params.get("dateStr") == null || params.get("target") == null) {
			return Response.error("没有传必要的参数");
		}

		if ("月度".equals(params.get("timeType").toString())) {
			return Response.error("数据库没有天数据！");
		}

		Map result = carbonService.carbonTrendAvg(params);

		return Response.ok(result);
	}

	@ApiOperation(value = "获取 碳排量子级 占比数据", notes = "接口备注：queryTotalObj : 以及 enName  合在一起", produces = "application/json")
	@PostMapping("subset")
	public Response carbonSunset (@RequestParam Map<String, Object> params) {

		if (params.get("timeType") == null || params.get("dateStr") == null || params.get("target") == null) {
			return Response.error("没有传必要的参数");
		}

		if ("月度".equals(params.get("timeType").toString())) {
			return Response.error("数据库没有天数据！");
		}

		Map result = carbonService.carbonSubset(params);

		return Response.ok(result);
	}

	@ApiOperation(value = "获取 单车碳排量子级 占比数据", notes = "接口备注：queryTotalObj : 以及 enName  合在一起", produces = "application/json")
	@PostMapping("avgSubset")
	public Response avgCarbonSunset (@RequestParam Map<String, Object> params) {

		if (params.get("timeType") == null || params.get("dateStr") == null || params.get("target") == null) {
			return Response.error("没有传必要的参数");
		}

		if ("月度".equals(params.get("timeType").toString())) {
			return Response.error("数据库没有天数据！");
		}

		Map result = carbonService.avgCarbonSunset(params);

		return Response.ok(result);
	}

	@ApiOperation(value = "获取 汇总 类型占比数据", notes = "接口备注：queryTotalObj : 以及 enName  合在一起", produces = "application/json")
	@PostMapping("carbonType")
	public Response carbonType (@RequestParam Map<String, Object> params) {

		if (params.get("timeType") == null || params.get("dateStr") == null || params.get("target") == null) {
			return Response.error("没有传必要的参数");
		}

		if ("月度".equals(params.get("timeType").toString())) {
			return Response.error("数据库没有天数据！");
		}

		Map result = carbonService.carbonType(params);

		return Response.ok(result);
	}

	@ApiOperation(value = "xxx能耗总揽--汇总", notes = "接口备注：queryTotalObj : 以及 enName  合在一起", produces = "application/json")
	@PostMapping("allin")
	public Response carbonType2 (@RequestParam Map<String, Object> params) {

		String[] types = new String[] { "总碳排", "总成本", "总用水", "总用电", "总燃气", "总冷量", "总蒸汽", "总空气" };
		String[] units = new String[] {"kg", "元", "吨", "℃", "Nm³", "kcal/h", "kg/h", "μg/m3"};
		List<Map> result = Lists.newArrayList();
		Random random = new Random();

		for (int i = 0; i < types.length; i++) {
			Map curMap = new HashMap(4);
			curMap.put("type", types[i]);
			int one = random.nextInt(59999) + 739887;
			double percent = random.nextDouble();
			curMap.put("useNum",
					new BigDecimal(one).multiply(new BigDecimal(percent)).setScale(2, RoundingMode.HALF_UP));
			curMap.put("planNum", one);
			curMap.put("percent", new BigDecimal(percent * 100).setScale(2, RoundingMode.HALF_UP) + "%");
			curMap.put("unit", units[i]);
			result.add(curMap);
		}
		return Response.ok(result);
	}

	@ApiOperation(value = "xxx能耗总揽--单车", notes = "接口备注：queryTotalObj : 以及 enName  合在一起", produces = "application/json")
	@PostMapping("avgs")
	public Response avgs (@RequestParam Map<String, Object> params) {

		String[] types = new String[] { "单车碳排", "单车成本", "单车用水", "单车电量", "单车燃气", "单车冷量", "单车蒸汽", "单车空气" };
		String[] units = new String[] {"kg", "元", "吨", "℃", "Nm³", "kcal/h", "kg/h", "μg/m3"};
		List<Map> result = Lists.newArrayList();
		Random random = new Random();

		for (int i = 0; i < types.length; i++) {
			Map curMap = new HashMap(4);
			curMap.put("type", types[i]);
			int one = random.nextInt(1500) + 1789;
			double percent = ( random.nextInt(13) + 85 ) * 0.01;
			curMap.put("useNum",
					new BigDecimal(one).multiply(new BigDecimal(percent)).setScale(2, RoundingMode.HALF_UP));
			curMap.put("planNum", one);
			curMap.put("percent", new BigDecimal(percent * 100).setScale(2, RoundingMode.HALF_UP) + "%");
			curMap.put("unit", units[i]);
			result.add(curMap);
		}
		return Response.ok(result);
	}

	@ApiOperation(value = "xxx能耗总揽--报表", notes = "接口备注：queryTotalObj : 以及 enName  合在一起", produces = "application/json")
	@PostMapping("form")
	public Response form (@RequestParam Map<String, Object> params) {

		List<Map<String, Object>> result = Lists.newArrayList();
		Random random = new Random();

		String time = params.get("time").toString();
		if (time == null){
			return Response.error("time不能为空");
		}
		if (time.length() == 4){
			DateTime stime1 = DateTime.parse(time).monthOfYear().withMinimumValue();
			int year = DateTime.parse(time).monthOfYear().getMaximumValue();
			for (int i = 1; i <= year; i++) {
					Map curMap = new HashMap(4);
					if (i > 1) {
						stime1 = stime1.plusMonths(1);
					}
					curMap.putIfAbsent("time", stime1.toString("yyyy-MM"));
					curMap.putIfAbsent("water", random.nextInt(130) + 1130);
					curMap.putIfAbsent("electricity", random.nextInt(210) + 112);
					curMap.putIfAbsent("gas", random.nextInt(450) + 1130);
					curMap.putIfAbsent("heat", random.nextInt(230) + 1130);
					curMap.putIfAbsent("airPress", random.nextInt(530) + 1180);
					result.add(curMap);
			}

		}if (time.length() == 7){
			DateTime stime = DateTime.parse(time).dayOfMonth().withMinimumValue();
			int maxDays = DateTime.parse(time).dayOfMonth().getMaximumValue();
			for (int i = 1; i <= maxDays; i++) {
				Map curMap = new HashMap(4);
				if (i > 1) {
					stime = stime.plusDays(1);
				}
				curMap.putIfAbsent("time", stime.toString("yyyy-MM-dd"));
				curMap.putIfAbsent("water", random.nextInt(130) + 1130);
				curMap.putIfAbsent("electricity", random.nextInt(210) + 112);
				curMap.putIfAbsent("gas", random.nextInt(450) + 1130);
				curMap.putIfAbsent("heat", random.nextInt(230) + 1130);
				curMap.putIfAbsent("airPress", random.nextInt(530) + 1180);
				result.add(curMap);
			}

		}if (time.length() == 10){
			DateTime stime1 = DateTime.parse(time).hourOfDay().withMinimumValue();
			int maxHour = DateTime.parse(time).hourOfDay().getMaximumValue();
			for (int i = 0; i <= maxHour; i++) {
				Map curMap = new HashMap(4);
				if (i > 0) {
					stime1 = stime1.plusHours(1);
				}
				curMap.putIfAbsent("time", stime1.toString("yyyy-MM-dd HH"));
				curMap.putIfAbsent("water", random.nextInt(130) + 1130);
				curMap.putIfAbsent("electricity", random.nextInt(210) + 112);
				curMap.putIfAbsent("gas", random.nextInt(450) + 1130);
				curMap.putIfAbsent("heat", random.nextInt(230) + 1130);
				curMap.putIfAbsent("airPress", random.nextInt(530) + 1180);
				result.add(curMap);
			}
		}

		// 汇总计算

		Map sums = result.stream().flatMap(map -> map.entrySet().stream())
				.filter(ma -> !"time".equals(ma.getKey().toString())).collect(Collectors.groupingBy(
						map1 -> map1.getKey(),
						Collectors.summingInt(map2 -> Integer.parseInt(map2.getValue().toString()))));
		sums.put("time", "累积量");
		result.add(sums);

		return Response.ok(result);
	}

	@ApiOperation(value = "xxx能耗总揽--能耗总揽--报表--能源详情数据", notes = "参数：time, energy, space", produces = "application/json")
	@PostMapping("formDetail")
	public Response loadDetail (@RequestParam String energy, @RequestParam String time, @RequestParam String space) {

		Map finalResult = new HashMap(2);
		if (energy == null) {
			return Response.error("必须传能源类型参数erergy");
		}
		List<Map<String, Object>> datas = Lists.newArrayList();
		List<Map<String, Object>> columns = Lists.newArrayList();

		Random random = new Random();
		// 生成一个随机 切分总数的份数
		int splitTimes = random.nextInt(4) + 3;


		if (time == null){
			return Response.error("time不能为空");
		}
		if (time.length() == 4){
			DateTime stime1 = DateTime.parse(time).monthOfYear().withMinimumValue();
			int year = DateTime.parse(time).monthOfYear().getMaximumValue();
			for (int i = 1; i <= year; i++) {
				Map curMap = new HashMap(4);
				if (i > 1) {
					stime1 = stime1.plusMonths(1);
				}
				curMap.putIfAbsent("time", stime1.toString("yyyy-MM"));
				// 生成N个随机数
				List<Integer> randomNums = randomNum(splitTimes, random);

				for (int j = 0; j < randomNums.size(); j++) {
					int randonStart = random.nextInt(199999) + 199999;
					curMap.putIfAbsent("item_"+j+"_start", randonStart);
					curMap.putIfAbsent("item_"+j+"_end", randonStart + randomNums.get(j));
					curMap.putIfAbsent("item_"+j+"_total", randomNums.get(j));
				}

				// 添加总和
				curMap.putIfAbsent("total", randomNums.stream().mapToInt(Integer::intValue).sum());
				datas.add(curMap);
			}

		}
		if (time.length() == 7){
			DateTime stime1 = DateTime.parse(time).dayOfMonth().withMinimumValue();
			int day = DateTime.parse(time).dayOfMonth().getMaximumValue();
			for (int i = 1; i <= day; i++) {
				Map curMap = new HashMap(4);
				if (i > 1) {
					stime1 = stime1.plusDays(1);
				}
				curMap.putIfAbsent("time", stime1.toString("yyyy-MM-dd"));
				// 生成N个随机数
				List<Integer> randomNums = randomNum(splitTimes, random);

				for (int j = 0; j < randomNums.size(); j++) {
					int randonStart = random.nextInt(199999) + 199999;
					curMap.putIfAbsent("item_"+j+"_start", randonStart);
					curMap.putIfAbsent("item_"+j+"_end", randonStart + randomNums.get(j));
					curMap.putIfAbsent("item_"+j+"_total", randomNums.get(j));
				}

				// 添加总和
				curMap.putIfAbsent("total", randomNums.stream().mapToInt(Integer::intValue).sum());
				datas.add(curMap);
			}
		}
		if (time.length() == 10){
			DateTime stime1 = DateTime.parse(time).hourOfDay().withMinimumValue();
			int maxHour = DateTime.parse(time).hourOfDay().getMaximumValue();
			for (int i = 0; i <= maxHour; i++) {
				Map curMap = new HashMap(4);
				if (i > 0) {
					stime1 = stime1.plusHours(1);
				}
				curMap.putIfAbsent("time", stime1.toString("yyyy-MM-dd HH"));
				// 生成N个随机数
				List<Integer> randomNums = randomNum(splitTimes, random);

				for (int j = 0; j < randomNums.size(); j++) {
					int randonStart = random.nextInt(199999) + 199999;
					curMap.putIfAbsent("item_"+j+"_start", randonStart);
					curMap.putIfAbsent("item_"+j+"_end", randonStart + randomNums.get(j));
					curMap.putIfAbsent("item_"+j+"_total", randomNums.get(j));
				}

				// 添加总和
				curMap.putIfAbsent("total", randomNums.stream().mapToInt(Integer::intValue).sum());
				datas.add(curMap);
			}
		}


		DateTime stime1 = DateTime.now().dayOfMonth().withMinimumValue();
		int maxDays = DateTime.now().dayOfMonth().getMaximumValue();
		/*for (int i = 1; i <= maxDays; i++) {
			Map curMap = new HashMap(4);
			if (i > 1) {
				stime1 = stime1.plusDays(1);
			}
			curMap.putIfAbsent("time", stime1.toString("yyyy-MM-dd"));
			// 生成N个随机数
			List<Integer> randomNums = randomNum(splitTimes, random);

			for (int j = 0; j < randomNums.size(); j++) {
				int randonStart = random.nextInt(199999) + 199999;
				curMap.putIfAbsent("item_"+j+"_start", randonStart);
				curMap.putIfAbsent("item_"+j+"_end", randonStart + randomNums.get(j));
				curMap.putIfAbsent("item_"+j+"_total", randomNums.get(j));
			}

			// 添加总和
			curMap.putIfAbsent("total", randomNums.stream().mapToInt(Integer::intValue).sum());
			datas.add(curMap);
		}*/

		// 添加到总Map
		finalResult.put("data", datas);
		// 遍历总数据，生成表头数据
		Map timeCol = new HashMap();
		timeCol.put("key", "time");
		timeCol.put("title", "时段");
		timeCol.put("width", 150);
		timeCol.put("fixed", "left");
		columns.add(timeCol);
		Map totalCol = new HashMap();
		totalCol.put("key", "total");
		totalCol.put("title", "汇总");
		totalCol.put("width", 150);
		totalCol.put("fixed", "left");
		columns.add(totalCol);
		String txt = "设备名称";
		for (int i = 0; i < splitTimes; i++) {
			Map curCol = new HashMap();
			curCol.put("title", txt+"_"+i);
			List<Map> childrenCols = Lists.newArrayList();
			String[] names = new String[] { "期始读数", "期末读数", "用量" };
			for (int j = 0; j < 3; j++) {
				Map curChildCol = new HashMap();
				if (j == 0) {
				curChildCol.put("key", "item_" + i + "_start");
				}
				if (j == 1) {
				curChildCol.put("key", "item_" + i + "_end");
				}
				if (j == 2) {
				curChildCol.put("key", "item_" + i + "_total");
				}
				curChildCol.put("title", names[j]);
				curChildCol.put("width", 160);
				childrenCols.add(curChildCol);
			}
			curCol.put("children", childrenCols);
			columns.add(curCol);
		}

		finalResult.put("column", columns);

		return Response.ok(finalResult);
	}

	public List randomNum (int times,Random random) {

		List<Integer> result = Lists.newArrayList();
		for (int i = 0; i < times; i++) {
			result.add(random.nextInt(1123) + 232);
		}
		return result;
	}

	@ApiOperation(value = "xxx能耗总揽--下载报表", notes = "下载文件", produces = "application/json")
	@PostMapping("dform")
	public void dform (@RequestParam Map<String, Object> params, HttpServletResponse response) {

		TemplateExportParams templateExportParams = new TemplateExportParams(getPicSavePath() + "/excel/qmonth.xlsx");

		Map<String, Object> excelMap = Maps.newHashMap();
		excelMap.put("maplist", Collections.emptyMap());
		Workbook workbook = ExcelExportUtil.exportExcel(templateExportParams, excelMap);
		OutputStream outputStream = null;
		try {
			//导出给前端下载
			String fileName = "能够下载到";
			response.setHeader("Content-Disposition",
					"attachment; filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
			response.setContentType("application/vnd.ms-excel; charset=UTF-8");

			outputStream = response.getOutputStream();
			workbook.write(outputStream);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * 获取 jar包所在 目录路径
	 *
	 * @return
	 */
	public String getPicSavePath ( ) {
		ApplicationHome home = new ApplicationHome(getClass());
		File jarFile = home.getSource();
		return jarFile.getParentFile().getParentFile().getAbsolutePath();
	}

	@ApiOperation(value = "xxx汇总碳排--总碳排,单车碳排,总产量,平均温度", notes = "参数 time 自由传参", produces = "application/json")
	@PostMapping("allCarBon")
	public Response carbonss (@RequestParam Map<String, Object> params) {
		List<Map> result = Lists.newArrayList();
		Random random = new Random();

		String[] types = new String[] { "总碳排", "单车碳排", "总产量", "平均温度" };
		String[] units = new String[] {"kg", "kg/辆", "辆", "℃"};
		Map curMap1 = new HashMap(4);
		int one = random.nextInt(15300) + 1789333;
		int one2 = random.nextInt(15300) + 1789333;
		curMap1.put("type", types[0]);
		curMap1.put("useNum", one);
		curMap1.put("unit", units[0]);
		int iu3 = random.nextInt(15) % 2;
		int iu4 = random.nextInt(15) % 2;
		curMap1.put("lastPeriod", ( iu3 == 0 ? "+" : "-" ) + random.nextInt(90) + "%");
		curMap1.put("kpi", ( iu4 == 0 ? "+" : "-" ) + random.nextInt(80) + "%");

		int production = random.nextInt(15300) + 20000;
		Map curMap3 = new HashMap(4);
		curMap3.put("type", types[2]);
		curMap3.put("unit", units[2]);
		curMap3.put("useNum", production);

		Map curMap2 = new HashMap(4);
		curMap2.put("type", types[1]);
		curMap2.put("unit", units[1]);
		curMap2.put("useNum", new BigDecimal(one).divide(new BigDecimal(production), 2, RoundingMode.HALF_UP)
		                                         .setScale(2, RoundingMode.HALF_UP));
		int iu = random.nextInt(15) % 2;
		curMap2.put("lastPeriod", ( iu == 0 ? "+" : "-" ) + random.nextInt(90) + "%");
		int iu2 = random.nextInt(15) % 2;
		curMap2.put("kpi", ( iu2 == 0 ? "+" : "-" ) + ( random.nextInt(80) + 17 ) + "%");

		double temp = random.nextInt(5) + 18 + random.nextDouble();
		Map curMap4 = new HashMap(4);
		curMap4.put("type", types[3]);
		curMap4.put("unit", units[3]);
		curMap4.put("useNum", new BigDecimal(temp).setScale(2, RoundingMode.HALF_UP));

		result.add(curMap1);
		result.add(curMap2);
		result.add(curMap3);
		result.add(curMap4);

		return Response.ok(result);
	}

	@ApiOperation(value = "xxx汇总碳排-- 碳排走势", notes = "参数 time 自由传参", produces = "application/json")
	@PostMapping("carbonTrend")
	public Response carbonssrr (@RequestParam Map<String, Object> params) {

		Map map = new HashMap();

		List<Map> result = Lists.newArrayList();
		Random random = new Random();

		List<String> xData = Lists.newArrayList();
		List<Object> yLeft = Lists.newArrayList();
		List<Object> yRight = Lists.newArrayList();

		for (int i = 1; i <= 12; i++) {
			xData.add(i + "月");
			yLeft.add(random.nextInt(1000) + 1223);
			yRight.add(random.nextInt(1000) + 1223);
		}

		map.put("xData", xData);
		map.put("yLeft", yLeft);
		map.put("yRight", yRight);

		return Response.ok(map);
	}

	@ApiOperation(value = "xxx汇总碳排-- 子级占比排名", notes = "参数: 顶部栏参数。分页参数：page（0 开始），size。不传分页参数，默认返回所有数据", produces = "application/json")
	@PostMapping("carbonTrendSon")
	public Response carbonssrssr (@RequestParam Map<String, Object> params) {

		Integer page = 0;
		Integer size = 7;

		if (params.get("page") != null) {
			 page = Integer.parseInt(params.get("page").toString());
		}
		if (params.get("size") != null) {
			size = Integer.parseInt(params.get("size").toString());
		}



		String[] types = new String[] { "HD1", "HD2", "ZZ", "DL", "HD3", "HD4", "ZZ1", "DL2", "HD7", "ZZ8", "DL5", "DL6", "HD45", "ZZ38", "DL54" };

		List<Map> result = Lists.newArrayList();
		Random random = new Random();

		for (int i = 0; i < types.length; i++) {

			Map cuMap = new HashMap();
			cuMap.put("type", types[i]);
			cuMap.put("useNum", random.nextInt(343433) + 343433);
			cuMap.put("riseRate", (random.nextInt(20) + 10) + "%");
			result.add(cuMap);
		}

		// 排序功能
		List<Map> userNum = result.stream().sorted(Comparator.comparingInt(
				Item -> Integer.parseInt(Item.get("useNum").toString()))).collect(Collectors.toList());
		Collections.reverse(userNum);

		for (int i = 0; i < userNum.size(); i++) {
			Map ddMap = userNum.get(i);
			ddMap.put("rank", i + 1);
		}

		Map finalR = new HashMap();
		finalR.put("totalElements", userNum.size());
		finalR.put("totalPages", new BigDecimal(userNum.size()/size).setScale(0, BigDecimal.ROUND_UP));
		finalR.put("size", size);
		finalR.put("content", userNum.stream().skip(page*size).limit(size).collect(Collectors.toList()));

		if (params.get("page") == null) {
			return Response.ok(userNum);
		} else {
			return Response.ok(finalR);
		}

	}

	@ApiOperation(value = "xxx汇总碳排-- 过往排名", notes = "参数: 顶部栏参数。分页参数：page（0 开始），size。不传分页参数，默认返回所有数据", produces = "application/json")
	@PostMapping("carbRanking")
	public Response carbonssrssrqz (@RequestParam Map<String, Object> params) {

		Integer page = 0;
		Integer size = 10;

		if (params.get("page") != null) {
			page = Integer.parseInt(params.get("page").toString());
		}
		if (params.get("size") != null) {
			size = Integer.parseInt(params.get("size").toString());
		}

		List<Map> result = Lists.newArrayList();
		Random random = new Random();

		for (int i = 2008; i < 2019; i++) {
			Map cuMap = new HashMap();
			cuMap.put("type", i);
			cuMap.put("useNum", random.nextInt(34343311) + 34113433);
			result.add(cuMap);
		}


		// 排序功能
		List<Map> userNum = result.stream().sorted(Comparator.comparingInt(
				Item -> Integer.parseInt(Item.get("useNum").toString()))).collect(Collectors.toList());
		Collections.reverse(userNum);

		for (int i = 0; i < userNum.size(); i++) {
			Map ddMap = userNum.get(i);
			ddMap.put("rank", i + 1);
		}

		Map finalR = new HashMap();
		finalR.put("totalElements", userNum.size());
		finalR.put("totalPages", new BigDecimal(userNum.size() / size).setScale(0, BigDecimal.ROUND_UP));
		finalR.put("size", size);
		finalR.put("content", userNum.stream().skip(page * size).limit(size).collect(Collectors.toList()));

		if (params.get("page") == null) {
			return Response.ok(userNum);
		} else {
			return Response.ok(finalR);
		}
	}

	@ApiOperation(value = "xxx汇总碳排-- 类型占比/排名", notes = "参数 time 自由传参", produces = "application/json")
	@PostMapping("typePercent")
	public Response carbonssrssrr (@RequestParam Map<String, Object> params,@RequestParam("summaryType") String summaryType) {
		int n=1;
		if(summaryType.equals("2")){
			n=2;
		}else if(summaryType.equals("3")){
			n=3;
		}else if(summaryType.equals("carbon")||summaryType.equals("1")){
			n=6;
		}
		String[] types=new String[n];
		switch (summaryType){
			case "carbon":   //汇总碳排
				types[0]="水";
				types[1]="燃气";
				types[2]="冷量";
				types[3]="压缩空气";
				types[4]="电";
				types[5]="其他";
				break;
			case "1":      //汇总成本
				types[0]="水";
				types[1]="燃气";
				types[2]="冷量";
				types[3]="压缩空气";
				types[4]="电";
				types[5]="其他";
				break;
			case "2":   //汇总用水
				types[0]="市政水";
				types[1]="处理水";
				break;
			case "3":   //汇总用电
				types[0]="市政电";
				types[1]="柴油电";
				types[2]="其他电";
				break;
			case "4":    //汇总燃气
				types[0]="燃气";
				break;
			case "5":   //汇总冷量
				types[0] = "冷量";
				break;
			case "6":   //汇总蒸汽
				types[0]="蒸汽";
				break;
			case "7":   //汇总空气
				types[0]="压缩空气";
				break;
		}
		List<Map> result = Lists.newArrayList();
		Random random = new Random();

		for (int i = 0; i < types.length; i++) {

			Map cuMap = new HashMap();
			cuMap.put("name", types[i]);
			cuMap.put("value", random.nextInt(343433) + 343433);
			result.add(cuMap);
		}

		Map finals = new HashMap();
		finals.put("datas", result);
		finals.put("legend", types);
		return Response.ok(finals);
	}

	@ApiOperation(value = "xxx汇总碳排-- 过往对比/过往排名", notes = "参数 time 自由传参", produces = "application/json")
	@PostMapping("lastCompare")
	public Response carbonssrssrrs (@RequestParam Map<String, Object> params) {

		List<String> xDatas = Lists.newArrayList();
		List<Object> yDatas = Lists.newArrayList();
		Random random = new Random();

		for (int i = 2007; i < 2018; i++) {
			xDatas.add(i + "年");
			yDatas.add(random.nextInt(34343311) + 34113433);
		}

		Map finals = new HashMap();
		finals.put("xDatas", xDatas);
		finals.put("yDatas", yDatas);
		return Response.ok(finals);

	}


	@ApiOperation(value = "xxx汇总碳排-- 同类对比", notes = "参数: 顶部栏参数。分页参数：page（0 开始），size。不传分页参数，默认返回所有数据", produces = "application/json")
	@PostMapping("sameCompare")
	public Response carbonsssrssrrs (@RequestParam Map<String, Object> params) {

		Integer page = 0;
		Integer size = 10;

		if (params.get("page") != null) {
			page = Integer.parseInt(params.get("page").toString());
		}
		if (params.get("size") != null) {
			size = Integer.parseInt(params.get("size").toString());
		}

		String[] types = new String[] { "东风日产", "广汽本田", "一汽丰田", "北京奔驰", "上海大众", "东风雷诺", "北京奔驰", "郑州日产", "北京现代", "吉利汽车",
		                                "小鹏汽车", "雷克萨斯", "东风红旗", "捷豹汽车" };

		List<Map> result = Lists.newArrayList();
		Random random = new Random();

		for (int i = 0; i < types.length; i++) {

			Map cuMap = new HashMap();
			cuMap.put("name", types[i]);
			int uu = random.nextInt(11) % 2;
			cuMap.put("useNum", random.nextInt(3433) + 3433);
			cuMap.put("increase", ( uu == 0 ? "+" : "-" ) + random.nextInt(100) + "%");

			result.add(cuMap);
		}

		// 排序功能
		List<Map> userNum = result.stream().sorted(Comparator.comparingInt(
				Item -> Integer.parseInt(Item.get("useNum").toString()))).collect(Collectors.toList());
		Collections.reverse(userNum);

		for (int i = 0; i < userNum.size(); i++) {
			Map ddMap = userNum.get(i);
			ddMap.put("rank", i + 1);
		}

		Map finalR = new HashMap();
		finalR.put("totalElements", userNum.size());
		finalR.put("totalPages", new BigDecimal(userNum.size() / size).setScale(0, BigDecimal.ROUND_UP));
		finalR.put("size", size);
		finalR.put("content", userNum.stream().skip(page * size).limit(size).collect(Collectors.toList()));

		if (params.get("page") == null) {
			return Response.ok(userNum);
		} else {
			return Response.ok(finalR);
		}
	}

	@ApiOperation(value = "xxx获取 日期的年月日树形数据", notes = "无参数", produces = "application/json")
	@GetMapping("ttrees")
	public Response loadDates (@RequestParam Integer year) {

		List<Map> toppest = Lists.newArrayList();
		Map yearMap = new HashMap();
		yearMap.put("value", year + "");
		yearMap.put("label", year + "年");
		List<Map> monthMapList = Lists.newArrayList();
		for (int j = 1; j < 13; j++) {
			// 遍历月份
			Map monthMap = new HashMap();
			String monthFlag = j < 10 ? "0" + j : j + "";
			monthMap.put("value", monthFlag);
			monthMap.put("label", j + "月");
			List<Map> dayMapList = Lists.newArrayList();
			DateTime sTime = DateTime.parse(year + "-" + monthFlag);
			Integer dayFlag = sTime.dayOfMonth().getMaximumValue();

			for (int k = 1; k <= dayFlag; k++) {
				// 遍历 日
				Map dayMap = new HashMap();
				String dayVlaue = k < 10 ? "0" + k : k + "";
				dayMap.put("value", dayVlaue);
				dayMap.put("label", k + "日");
				dayMapList.add(dayMap);
			}
			monthMap.put("children", dayMapList);
			monthMapList.add(monthMap);
		}
		yearMap.put("children", monthMapList);
		toppest.add(yearMap);

		return Response.ok(toppest);
	}

}
